package com.djzhou.gmms.util.cookie;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;

import com.djzhou.gmms.model.user.TbUser;


public class CookieUtil {
	public static final String USER_COOKIE = "gmms.userCookie";

	// 添加一个cookie
	public static Cookie addCookie(TbUser user) {
		Cookie cookie = new Cookie(USER_COOKIE, user.getLoginName() + ","+ user.getLoginPwd());
		cookie.setMaxAge(60 * 60 * 24 * 14);// cookie保存两周
		return cookie;
	}

	// 得到cookie
	public static String getCookie(HttpServletRequest request) {
		Cookie[] cookies = request.getCookies();
		String cookieValue=null;
		System.out.println("cookies: " + cookies);
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if (CookieUtil.USER_COOKIE.equals(cookie.getName())) {
					String value = cookie.getValue();
					if (StringUtils.isNotBlank(value)) {
						cookieValue=value;
					}
				}
			}
		}
		return cookieValue;
	}

	// 删除cookie
	public static Cookie delCookie(HttpServletRequest request) {
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if (USER_COOKIE.equals(cookie.getName())) {
					cookie.setValue("");
					cookie.setMaxAge(0);
					return cookie;
				}
			}
		}
		return null;
	}
}
